<?
$layout='layout_index.htm';
$headers='';
$content='';

//routing
if(!empty($_GET['page']))switch($_GET['page']){
	case 'some_custom_page': break;
	default:
	  if( $f=load_file('content_'.$_GET['page'].'.htm') ){
	    if(!empty($f['layout']))	$layout=trim($f['layout']);
	    if(!empty($f['headers'])) $headers=trim($f['headers']);
	    if(!empty($f['content'])) $content=$f['content'];
		}
}
$layout=load_file($layout);

//Output
$res=strjtr( $layout, array(
	'headers'=>$headers,
	'content'=>$content,
));
$rega='~\{file:([^\}]+)\}~';
preg_match_all($rega, $res, $m);
if(!empty($m)) for($i=0; $i<count($m[1]);$i++ ){
	$res=str_replace( $m[0][$i], load_file( trim($m[1][$i]) ), $res );
}
echo $res;


//Helpers
function strjtr_addbraces($item){return '{'.$item.'}';}
function strjtr($str,$arr){return str_replace( array_map( 'strjtr_addbraces', array_keys($arr) ) , array_values($arr), $str);}
function load_file($f){
	if(empty($f) || !file_exists($f)) return false;

	// разбор шаблона по секциям
	$res = file_get_contents($f);
	$match=preg_split('/^\[(.+)\](.*)/m',$res,-1,PREG_SPLIT_DELIM_CAPTURE);
	if (count($match)==1) return $res;

	$rs=array(); $j=count($match)-1;
	for ($i=0;$i<$j;$i+=3)
		$rs[$match[$i+1]]=trim($match[$i+3]);
	return $rs;
}

?>
